import { getUser, addUser, updateUser, checkUsernameUnique, checkEmailUnique, checkPhoneUnique } from '@/api/system/user'
import { queryTree } from '@/api/system/dept'
import SelectDept from '@/components/pt/selectDept/SelectDept'
import AntModal from '@/components/pt/dialog/AntModal'
export default {
  name: 'CreateForm',
  props: {
    deptCheckedValue: {
      type: Object
    },
    defalutExpandedKeys: {
      type: Array
    }
  },
  components: {
    AntModal,
    SelectDept
  },
  data () {
    const validateDeptId = (rule, value, callback) => {
      if (value.deptIds === '' || value.deptIds === undefined || value.deptIds === null) {
        callback(new Error('部门不允许为空'))
      } else {
        callback()
      }
    }
    return {
      expandedKeys: this.defalutExpandedKeys,
      spinning: false,
      delayTime: 100,
      replaceFields: { children: 'children', title: 'label', key: 'id', value: 'id' },
      customStyle: 'background: #fff;ssborder-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden',
      // 角色选项
      roleOptions: [],
      // 默认密码
      initPassword: undefined,
      formTitle: '',
      // 表单参数
      form: {
        userId: undefined,
        deptId: 0,
        username: undefined,
        password: undefined,
        phone: undefined,
        email: undefined,
        sex: '1',
        status: '1',
        userType: '0',
        roleIds: []
      },
      open: false,
      rules: {
        name: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
        username: [{ required: true, message: '登录名不能为空', trigger: 'blur' },
         { validator: this.checkUsernameUnique, trigger: 'change' }
        ],
        secretLevel: [{ required: true, message: '密级不能为空', trigger: 'blur' }],
        deptId: [{ required: true, message: '部门不能为空', trigger: 'blur', validator: validateDeptId }],
        email: [
          {
            type: 'email',
            message: '请正确填写邮箱地址',
            trigger: ['blur', 'change']
          },
          { validator: this.checkEmailUnique }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请正确填写手机号',
            trigger: 'blur'
          },
          { validator: this.checkPhoneUnique }
        ]
      }
    }
  },
  filters: {},
  created () {
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.data
    })
  },
  computed: {},
  watch: {},
  methods: {
    // 取消按钮
    cancel () {
      this.open = false
      this.$emit('close')
    },
    // 表单重置
    reset () {
      if (this.$refs.form !== undefined) {
        this.$refs.form.resetFields()
      }
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.open = true
      this.formTitle = '新增用户'
      this.form.password = this.initPassword
      getUser().then(response => {
        this.roleOptions = response.data.roles
        this.form.deptId = { deptIds: '', names: '' }
      })
    },
    /** 修改按钮操作 */
    handleUpdate (row, userIds) {
      this.open = true
      this.formTitle = `修改【${row.username}】信息`
      this.spinning = !this.spinning
      const userId = row ? row.userId : userIds
      getUser(userId).then(response => {
        this.form = response.data.user
        this.form.deptId = { deptIds: response.data.user.deptId, names: response.data.user.deptName }
        this.roleOptions = response.data.roles
        this.form.roleIds = response.data.roleIds
        this.spinning = !this.spinning
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          const saveForm = JSON.parse(JSON.stringify(this.form))
          if (this.form.deptId !== undefined) {
            saveForm.deptId = this.form.deptId.deptIds
          }
          if (this.form.userId !== undefined) {
            updateUser(saveForm).then(response => {
              this.$message.success(
                '修改成功',
                3
              )
              this.open = false
              this.$emit('ok')
            })
          } else {
            addUser(saveForm).then(response => {
              this.$message.success(
                '新增成功',
                3
              )
              this.open = false
              this.$emit('ok')
            })
          }
        } else {
          return false
        }
      })
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        queryTree({ deptId: treeNode.dataRef.deptId }).then(response => {
            treeNode.dataRef.children = response.data
            resolve()
        })
      })
    },
    checkUsernameUnique (rule, value, callback) {
      const msg = '登陆名称已存在'
      if (value === '') {
        callback()
      } else {
        const checkData = {
          username: value,
          userId: this.form.userId !== undefined ? this.form.userId : ''
        }
        checkUsernameUnique(checkData).then(response => {
          if (response.data === true) {
            callback()
          } else {
            callback(msg)
          }
        })
      }
    },
    checkEmailUnique (rule, value, callback) {
      const msg = '邮箱已存在'
      if (value === '') {
        callback()
      } else {
        const checkData = {
          email: value,
          userId: this.form.userId !== undefined ? this.form.userId : ''
        }
        checkEmailUnique(checkData).then(response => {
          if (response.data === true) {
            callback()
          } else {
            callback(msg)
          }
        })
      }
    },
    checkPhoneUnique (rule, value, callback) {
      const msg = '手机号已存在'
      if (value === '') {
        callback()
      } else {
        const checkData = {
          phone: value,
          userId: this.form.userId !== undefined ? this.form.userId : ''
        }
        checkPhoneUnique(checkData).then(response => {
          if (response.data === true) {
            callback()
          } else {
            callback(msg)
          }
        })
      }
    }
  }
}
